var laypage, layer;
layui.use(['laydate', 'form', 'laypage', 'layer'], function () {
    var laydate = layui.laydate;
    var form = layui.form;
    laypage = layui.laypage;
    layer = layui.layer;

    // 监听全选
    form.on('checkbox(checkall)', function (data) {

        if (data.elem.checked) {
            $('tbody input').prop('checked', true);
        } else {
            $('tbody input').prop('checked', false);
        }
        form.render('checkbox');
    });

    //执行一个laydate实例
    laydate.render({
        elem: '#start' //指定元素
    });

    //执行一个laydate实例
    laydate.render({
        elem: '#end' //指定元素
    });
    //监听提交
    form.on('submit(sreach)',
        function (data) {
            findAll();
            return false;
        });
    laypage.render({
        elem: 'page'
        , count: sessionStorage.getItem("totalCount")
        // , layout: ['prev', 'next']
        , theme: '#1E9FFF'
        , jump: function (obj, first) {
            // if (first) {
                sessionStorage.setItem("curPage", obj.curr);
                findAll();
            // }
        }
    });

});
$(function () {
    // findAll();
});


// function setTotalCount() {
//     findAll();
//     console.log("a");
//     return sessionStorage.getItem("totalCount");
// }

/*用户-停用*/
function member_stop(obj, id) {
    layer.confirm('确认要停用吗？', function (index) {

        //需要在后台去修改状态
        updateEnable(id);
        if ($(obj).attr('title') == '启用') {

            //发异步把用户状态进行更改
            $(obj).attr('title', '停用')
            $(obj).find('i').html('&#xe62f;');

            $(obj).parents("tr").find(".td-status").find('span').addClass('layui-btn-disabled').html('已停用');
            layer.msg('已停用!', {icon: 5, time: 1000});

        } else {
            $(obj).attr('title', '启用')
            $(obj).find('i').html('&#xe601;');

            $(obj).parents("tr").find(".td-status").find('span').removeClass('layui-btn-disabled').html('已启用');
            layer.msg('已启用!', {icon: 5, time: 1000});
        }

    });
}

function updateEnable(id) {
    $.ajax({
        url: '/back/user/enable',
        data: {id: id},
        type: 'post',
        dataType: 'json',
        success: function (data) {
            findAll();
        }
    })
}

/*用户-删除*/
function member_del(obj, id) {
    layer.confirm('确认要删除吗？', function (index) {
        $.ajax({
            url: '/back/user/delete',
            data: {id: id},
            type: 'post',
            dataType: 'json',
            success: function (data) {
                if (data.result == "success") {
                    //发异步删除数据
                    $(obj).parents("tr").remove();
                    layer.msg('已删除!', {icon: 1, time: 1000});
                }
            }
        })

    });
}


function delAll(argument) {
    var ids = [];

    // 获取选中的id
    $('tbody input').each(function (index, el) {
        if ($(this).prop('checked')) {
            ids.push($(this).val())
        }
    });

    layer.confirm('确认要删除吗？' + ids.toString(), function (index) {
        //捉到所有被选中的，发异步进行删除
        layer.msg('删除成功', {icon: 1});
        $(".layui-form-checked").not('.header').parents('tr').remove();
    });
}

function getFormData() {
    return {
        username: $("#username").val(),
        phone: $("#phone").val(),
        sex: $("#sex").val(),
        hobby: getHobby().toLocaleString(),
        startBirthday: $("#start").val(),
        endBirthday: $("#end").val(),
        curPage: sessionStorage.getItem("curPage"),
    };

}

function getHobby() {
    let vals = [];//数组的赋值
    $("input[type=checkbox][name=hobby]:checked").each(function (index, item) {
        vals.push($(this).val());
    });
    return vals;
}

function findAll() {
    // $.ajax({
    //     url: '/back/user/get',
    //     data: getFormData(),
    //     type: 'get',
    //     dataType: 'json',
    //     success: function (data) {
    //         console.log(data);
    //         sessionStorage.setItem("totalCount", data.totalCount);
    //         setData(data.list);
    //         setPage();
    //     }
    // }
    let data = myAjax("/back/user/get", getFormData(), "get");
    console.log(data);
    if (data) {
        sessionStorage.setItem("totalCount", data.totalCount);
        setData(data.list);
        // setPage();
    }

}

function setPage() {
    //只显示上一页、下一页
    laypage.render({
        elem: 'page'
        , count: sessionStorage.getItem("totalCount")
        // , layout: ['prev', 'next']
        , theme: '#1E9FFF'
        , jump: function (obj, first) {
            if (!first) {
                sessionStorage.setItem("curPage", obj.curr);
                findAll();
            }
        }
    });
}

function setData(data) {
    let html = '';
    if (data == null) {
        return;
    }
    for (let i = 0; i < data.length; i++) {
        html += '<tr>\n' +
            '                                    <td>' + data[i].id + '</td>\n' +
            '                                    <td>' + data[i].username + '</td>\n' +
            '                                    <td>' + data[i].sex + '</td>\n' +
            '                                    <td>' + data[i].phone + '</td>\n' +
            '                                    <td>' + data[i].email + '</td>\n' +
            '                                    <td>' + data[i].hobby + '</td>\n' +
            '                                    <td class="td-status">\n' +
            '                                      <span class="layui-btn layui-btn-normal layui-btn-mini">' + (data[i].enable == 1 ? '已启用' : '已停用') + '</span></td>\n' +
            '                                    <td class="td-manage">\n' +
            '                                      <a onclick="member_stop(this,' + data[i].id + ')" href="javascript:;"  title="' + (data[i].enable == 1 ? "停用" : "启用") + '">\n' +
            '                                        <i class="layui-icon">&#xe60d;</i>\n' +
            '                                      </a>\n' +
            '                                      <a title="编辑"  onclick="edit(' + data[i].id + ')" href="javascript:;">\n' +
            '                                        <i class="layui-icon">&#xe642;</i>\n' +
            '                                      </a>\n' +
            '                                      <a onclick="xadmin.open(\'修改密码\',\'member-password.html\',600,400)" title="修改密码" href="javascript:;">\n' +
            '                                        <i class="layui-icon">&#xe631;</i>\n' +
            '                                      </a>\n' +
            '                                      <a title="删除" onclick="member_del(this,' + data[i].id + ')" href="javascript:;">\n' +
            '                                        <i class="layui-icon">&#xe640;</i>\n' +
            '                                      </a>\n' +
            '                                    </td>\n' +
            '                                  </tr>';
    }
    $("#tbody").html(html);

}

function edit(id) {
    sessionStorage.setItem("userId", id);
    xadmin.open('用户编辑', 'user-edit.html', 600, 400);
}